package com.rem.shiro.eeShiro.my3CustAuthentication;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * 自定义realm 认证
 *
 * @author Rem
 * @date 2021-04-03
 */

public class TestCustMD5RealmAuthenticator {

    public static void main(String[] args) {
        //1.创建安全管理器
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        //2.给安全管理器设置 自定义MD5realm
        CustomerMD5Realm customerMD5Realm= new CustomerMD5Realm();
        //默认密码匹配是equals  需要换凭证匹配器 换成md5匹配就完成了人认证
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher("md5");
        //添加散列次数
        hashedCredentialsMatcher.setHashIterations(1024);
        customerMD5Realm.setCredentialsMatcher(hashedCredentialsMatcher);
        securityManager.setRealm(customerMD5Realm);
        //3.给全局安全工具类 放入安全管理器
        SecurityUtils.setSecurityManager(securityManager);
        //4.subject主体
        Subject subject = SecurityUtils.getSubject();
        //5.创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");
        //6.登陆认证

        //验证状态
        System.out.println("是否认证:" + subject.isAuthenticated());
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            System.err.println("用户名错误");
            e.printStackTrace();
        } catch (IncorrectCredentialsException e) {
            System.err.println("密码错误");
            e.printStackTrace();
        }

        //验证状态
        System.out.println("是否认证:" + subject.isAuthenticated());

    }
}
